package com.hualan.sfzyproject.controller.admin;

import com.hualan.sfzyproject.util.AliOssUtil;
import com.hualan.sfzyproject.util.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/admin")
public class UploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public R upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            UUID uuid = UUID.randomUUID();
            String objectName = uuid + suffix;
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return R.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }

        return R.error("UPLOAD_FAILED");
    }
}
